//
//  WQOAuthViewController.swift
//  WeiBo
//
//  Created by 张德华 on 7/23/16.
//  Copyright © 2016 ZhangDeHua. All rights reserved.
//

import UIKit

class WQOAuthViewController: UIViewController {
    
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
        ///------ 网络请求
        webView.loadRequest(NSURLRequest(URL: WQNetworkTools.sharedManager.oAuthURL))
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        progressView.removeProgress()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
    }
    
    // MARK: - ************界面设置
    func setupUI() {
        
        ///------ 添加自定义进度条
        navigationController?.navigationBar.insertSubview(progressView, belowSubview: (navigationController?.navigationBar)!)
        
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(WQOAuthViewController.cancelButtonClicked))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(WQOAuthViewController.autoFillButtonClicked))
    }
    
    
    
    // MARK: - ************导航按钮监听事件
    @objc func cancelButtonClicked() {
        print("oAuthVc->取消按钮")
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc func autoFillButtonClicked() {
        print("oAuthVc->自动填充按钮")
        
        ///------ 自动填充用户名和密码,进行授权
        let jsString = "document.getElementById('userId').value='\(wq_name)',document.getElementById('passwd').value='\(wq_password)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    // MARK: - ************懒加载
    private lazy var webView = UIWebView()
    ///------ 自定义进度条
    private lazy var progressView: WQOAuthProgressView = WQOAuthProgressView()
    
}


extension WQOAuthViewController: UIWebViewDelegate {
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.startAnim()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.endAnim()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("OAuth请求出错\(error)")
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        
        if let u = urlString where u.hasPrefix(redirectUri) {
            
            let quey = request.URL?.query
            if let q = quey {
                ///------ 1. 获取请求码 code
                let code = q.substringFromIndex("code=".endIndex)
                print("请求成功->code码:\(code)")
                
                ///------ 2. 获取access_token
                WQNetworkTools.sharedManager.loadAccesToken(code, finished: { (result) in
                    
                    guard let result = result else {
                        print("您的网络不给力") 
                        return
                    }
                    print(result)
                    
                    
                    WQUserAccountModel.sharedUserAccount.updateUserAccount(result)
                   
                    
                    ///------ 登录成功发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WQWeiBoLoginSuccessedNotification, object: nil)
                })
            }
        }
        return true
    }
}

